package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threablocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;

    @Value("${file.oss.prefix}")
    String prefix;
    @Value("${file.oss.web-site}")
    String webSite;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //校验参数 文件不能为空 文件size
        if (multipartFile == null || multipartFile.getSize() == 0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"请上传正确的文件信息");
        }
        //校验文件格式是否正确 暂时支持后缀：【jpg jpeg gif png】
        //校验用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //上传文件到oss path文件路径
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        fileName = fileName + suffix;
        try {
            fileStorageService.store(prefix, fileName, multipartFile.getInputStream());
            //封装素材实例对象
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(user.getId());
            wmMaterial.setUrl(fileName);
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short)0);
            wmMaterial.setCreatedTime(new Date());
            //保存素材
            save(wmMaterial);
            wmMaterial.setUrl(webSite + wmMaterial.getUrl());
            return ResponseResult.okResult();
        } catch (IOException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"文件上传失败，请稍后重试");
        }
        //返回结果
        return null;
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //校验参数
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请先登录");
        }
        //封装查询条件
        //  分页参数
        IPage ipage = new Page(dto.getPage(), dto.getSize());
        //  查询条件
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.<WmMaterial>lambdaQuery();
        if (dto.getIsCollection() != null && dto.getIsCollection().intValue() == 1) {
            queryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        queryWrapper.eq(WmMaterial::getUserId, user.getId());
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        //执行得到结果
        IPage<WmMaterial> page = page(ipage, queryWrapper);
        List<WmMaterial> records = ipage.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite + record.getUrl());
        }
        //遍历结果，添加访问前缀
        return new PageResponseResult(dto.getPage(), dto.getSize(), ipage.getTotal(), records);
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult delPicture(Integer id) {
        //1.校验参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"素材id不能为空");
        }
        //2.根据id查询素材
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该素材不存在");
        }
        //3.判断当前素材是否被引用
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (count > 0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该素材已被引用，无法删除");
        }
        //4.删除素材信息
        removeById(id);
        //5.在oss中删除对应的素材图片信息
        fileStorageService.delete(wmMaterial.getUrl());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.校验参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "id不能为空");
        }
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection,type)
                .eq(WmMaterial::getId,id)
        );
        return ResponseResult.okResult();
    }
}
